﻿using System;
using System.Linq;
using System.Windows.Navigation;

using SSTU.Extensions;
using SSTU.ViewModel;
using SSTU.ViewModel.Item;

using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Text.RegularExpressions;

namespace SSTU.View
{
	/// <summary>
	/// Page for the group time table.
	/// </summary>
	public partial class GroupTimeTablePage : PhoneApplicationPage
	{
		public const string NavigationParameterNameGroupId = "GroupId";
		public const string NavigationParameterNameGroupShortName = "GroupShortName";
		public const string NavigationParameterNameGroupLongName = "GroupLongName";

		/// <summary>
		/// Initializes a new instance of the <see cref="GroupTimeTablePage"/> class.
		/// </summary>
		public GroupTimeTablePage()
		{
			InitializeComponent();
			AddTileButton = new ApplicationBarIconButton(new Uri("/Controls/Assets/Appbar.Pin.png", UriKind.Relative)) { Text = "закрепить" };
			AddTileButton.Click += OnAddTileMenuItemClick;
		}

		/// <summary>
		/// Gets or sets the view model for page.
		/// </summary>
		public GroupTimeTableViewModel ViewModel
		{
			get { return DataContext as GroupTimeTableViewModel; }
			set { DataContext = value; }
		}

		/// <summary>
		/// Gets or sets application bar menu item for adding this page to the desktop.
		/// </summary>
		public ApplicationBarIconButton AddTileButton { get; set; }

		/// <summary>
		/// Called when a page becomes the active page in a frame.
		/// </summary>
		/// <param name="e">An object that contains the event data.</param>
		protected override void OnNavigatedTo(NavigationEventArgs e)
		{
			var viewModel = ViewModel;
			if (viewModel != null)
			{
				string groupId = NavigationContext.QueryString.Get(NavigationParameterNameGroupId);
				string groupShortName = NavigationContext.QueryString.Get(NavigationParameterNameGroupShortName);
				string groupLongName = NavigationContext.QueryString.Get(NavigationParameterNameGroupLongName);
				var groupItem = new GroupItemVM(groupId, groupShortName, groupLongName, FavoriteState.Unknown);
				viewModel.Initialize(groupItem);
				UpdateFavoriteMenuItem();
				viewModel.Group.FavoriteStateChanged += OnViewModelGroupFavoriteStateChanged;
				// Initialize menu item for tile's adding.
				var existingShellTile = ShellTile
					.ActiveTiles
					.FirstOrDefault(st =>
					{
						bool isUriForGroupTimeTablePage = viewModel.NavigationInteraction.IsGroupTimeTableUri(st.NavigationUri, groupId);
						return isUriForGroupTimeTablePage;
					});
				if (existingShellTile == null)
				{
					ApplicationBar.Mode = ApplicationBarMode.Default;
					if (!ApplicationBar.Buttons.Contains(AddTileButton))
					{
						ApplicationBar.Buttons.Add(AddTileButton);
					}
					AddTileButton.IsEnabled = true;
				}
				else
				{
					ApplicationBar.Mode = ApplicationBarMode.Default;
					if (!ApplicationBar.Buttons.Contains(AddTileButton))
					{
						ApplicationBar.Buttons.Add(AddTileButton);
					}
					AddTileButton.IsEnabled = false;
				}
			}
		}

		/// <summary>
		/// Called when add tile menu item clicked.
		/// </summary>
		/// <param name="sender">The sender.</param>
		/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
		private void OnAddTileMenuItemClick(object sender, EventArgs e)
		{
			var viewModel = ViewModel;
			if ((NavigationService != null)
				&& (NavigationService.CurrentSource != null)
				&& (viewModel != null)
				&& (viewModel.Group != null)
				&& !string.IsNullOrEmpty(viewModel.Group.Id))
			{
				var existingShellTile = ShellTile
					.ActiveTiles
					.FirstOrDefault(st =>
					{
						bool isUriForGroupTimeTablePage = viewModel.NavigationInteraction.IsGroupTimeTableUri(st.NavigationUri, viewModel.Group.Id);
						return isUriForGroupTimeTablePage;
					});
				if (existingShellTile == null)
				{
					ShellTile.Create(NavigationService.CurrentSource, new StandardTileData()
					{
						Title = viewModel.Group.ShortName,
						BackgroundImage = new Uri("Background.png", UriKind.Relative),
					});
				}
			}
		}

		/// <summary>
		/// Called when a page is no longer the active page in a frame.
		/// </summary>
		/// <param name="e">An object that contains the event data.</param>
		protected override void OnNavigatedFrom(NavigationEventArgs e)
		{
			if (ViewModel != null)
			{
				ViewModel.Group.FavoriteStateChanged -= OnViewModelGroupFavoriteStateChanged;
			}
		}

		/// <summary>
		/// Called when[view model group favorite state changed.
		/// </summary>
		/// <param name="sender">The sender.</param>
		/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
		protected void OnViewModelGroupFavoriteStateChanged(object sender, EventArgs e)
		{
			UpdateFavoriteMenuItem();
		}

		/// <summary>
		/// Updates the menu item for changing favorite state of the group.
		/// </summary>
		/// <param name="newFavoriteState">New value of the group 'FavoriteState'.</param>
		protected void UpdateFavoriteMenuItem()
		{
			var viewModel = ViewModel;
			if (viewModel !=null )
			{
				var favoriteMenuItem = ApplicationBar.MenuItems[0] as ApplicationBarMenuItem;
				favoriteMenuItem.IsEnabled = viewModel.FavoriteCommand.CanExecute(viewModel.Group);
				favoriteMenuItem.Text = viewModel.Group.FavoriteCommandCaption;
			}
		}

		/// <summary>
		/// Called when favorite menu item clicked.
		/// </summary>
		/// <param name="sender">The sender.</param>
		/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
		private void OnFavoriteMenuItemClick(object sender, EventArgs e)
		{
			var viewModel = ViewModel;
			if (viewModel != null)
			{
				if (viewModel.FavoriteCommand.CanExecute(viewModel.Group))
				{
					viewModel.FavoriteCommand.Execute(viewModel.Group);
				}
			}
		}
	}
}